package com.example.weight.greenSeasons.waterDeal;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DeodorizationTable extends AppCompatActivity {
    private TitleBar titleBar;
    private String name, factory;

    //除臭日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date deodorizationDate = new Date(System.currentTimeMillis());
    private TextView deodorization_date;
    //卸粪车间用量
    private TextView xieFen_weight;
    //固液分离系统用量
    private TextView guYeFenLi_weight;
    //絮凝系统用量
    private TextView xuNing_weight;
    //堆肥系统用量
    private TextView duiFei_weight;
    //户外空间用量
    private TextView huWai_weight;
    //酵素重
    private TextView jiaoSu_weight;
    //其他药剂重
    private TextView qiTaYaoJi_weight;
      //备注
    private EditText remark;
    String activeButton = new String();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deodorization);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                DeodorizationTable.this.finish();
            }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        /**
         * 显示设置日期
         */
        deodorization_date = findViewById(R.id.deodorization_date);
        deodorization_date.setText(simpleDateFormat.format(deodorizationDate));
        /**
         *7个重量
         */
        //卸粪车间用量
        xieFen_weight = findViewById(R.id.xieFen_weight);
        //固液分离系统用量
        guYeFenLi_weight = findViewById(R.id.guYeFenLi_weight);
        //絮凝系统用量
        xuNing_weight = findViewById(R.id.xuNing_weight);
        //堆肥系统用量
        duiFei_weight = findViewById(R.id.duiFei_weight);
        //户外空间用量
        huWai_weight = findViewById(R.id.huWai_weight);
        //酵素重
        jiaoSu_weight = findViewById(R.id.jiaoSu_weight);
        //其他药剂重
        qiTaYaoJi_weight = findViewById(R.id.qiTaYaoJi_weight);
        remark = findViewById(R.id.deodorization_remark);


        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/deodorizationCraft/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!data.isNull("id") && data.getString("factory").equals(factory)) {
                                //deodorization_date.setHint(data.getString("incomeDate"));
                                xieFen_weight.setText(data.getString("dungWeight"));
                                guYeFenLi_weight.setText(data.getString("solidliquidWeight"));
                                xuNing_weight.setText(data.getString("flocculationWeight"));
                                duiFei_weight.setText(data.getString("compostWeight"));
                                huWai_weight.setText(data.getString("outdoorWeight"));
                                jiaoSu_weight.setText(data.getString("enzymeWeight"));
                                qiTaYaoJi_weight.setText(data.getString("othersWeight"));
                                remark.setText(data.getString("remarks"));
                                Toast.makeText(DeodorizationTable.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DeodorizationTable.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "xieFen_weight_btn":
                xieFen_weight.setText(weight);
                break;
            case "guYeFenLi_weight_btn":
                guYeFenLi_weight.setText(weight);
                break;
            case "xuNing_weight_btn":
                xuNing_weight.setText(weight);
                break;
            case "duiFei_weight_btn":
                duiFei_weight.setText(weight);
                break;
            case "huWai_weightt_btn":
                huWai_weight.setText(weight);
                break;
            case "jiaoSu_weight_btn":
                jiaoSu_weight.setText(weight);
                break;
            case "qiTaYaoJi_weight_btn":
                qiTaYaoJi_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.xieFen_weight_btn:
                activeButton = "xieFen_weight_btn";
                break;
            case R.id.guYeFenLi_weight_btn:
                activeButton = "guYeFenLi_weight_btn";
                break;
            case R.id.xuNing_weight_btn:
                activeButton = "xuNing_weight_btn";
                break;
            case R.id.duiFei_weight_btn:
                activeButton = "duiFei_weight_btn";
                break;
            case R.id.huWai_weight_btn:
                activeButton = "huWai_weight_btn";
                break;
            case R.id.jiaoSu_weight_btn:
                activeButton = "jiaoSu_weight_btn";
                break;
            case R.id.qiTaYaoJi_weight_btn:
                activeButton = "qiTaYaoJi_weight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(DeodorizationTable.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    public void save(View view) {
        if (xieFen_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写卸粪车间用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (guYeFenLi_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写固液分离系统用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (xuNing_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写絮凝系统用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (duiFei_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写堆肥系统用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (huWai_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写户外空间用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (jiaoSu_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写酵素用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (qiTaYaoJi_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写其他药剂用量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) ->{
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/deodorizationCraft/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("LB", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(DeodorizationTable.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DeodorizationTable.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DeodorizationTable.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
//                            map.put("deodorizationDate", simpleDateFormat.format(deodorizationDate));
                            map.put("dung_weight", xieFen_weight.getText().toString());
                            map.put("solidliquid_weight",guYeFenLi_weight.getText().toString());
                            map.put("flocculation_weight", xuNing_weight.getText().toString());
                            map.put("compost_weight", duiFei_weight.getText().toString());
                            map.put("outdoor_weight", huWai_weight.getText().toString());
                            map.put("enzyme_weight", jiaoSu_weight.getText().toString());
                            map.put("others_weight", qiTaYaoJi_weight.getText().toString());
                            map.put("recorder",name);
                            map.put("remarks", ((TextView) findViewById(R.id.deodorization_remark)).getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}